package com.example.ticketingserver.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ticketingserver.dto.R;
import com.example.ticketingserver.entity.Station;
import com.example.ticketingserver.service.StationService;
import com.example.ticketingserver.utils.QiniuOssUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import static com.baomidou.mybatisplus.extension.toolkit.Db.getOne;

@CrossOrigin //开启不同源的访问，允许来自任何源的访问。
@Tag(name = "站台接口",description = "站台相关功能接口，包含：添加，删除，列表查询")
@RestController
public class StationController {
    @Autowired
    private StationService stationService;
    @Operation(summary = "车站添加",description = "需要提供车站名称")
    @Parameters({
            @Parameter(name = "station",description = "车站资源文本信息，名称，等级，图片等"),
            @Parameter(name = "myfile",description = "上传的车站的图片")
    })
    @PostMapping("/station/reg")
    public R add(@Parameter(description = "车站")Station station,MultipartFile myfile) throws IOException {
//获取查询条件构造器
        QueryWrapper<Station> query = Wrappers.query(Station.class);
        query.eq("name",station.getName());
        //执行查询
        Station one = getOne(query);
        if(Objects.nonNull(one)){
            return R.fail().setMsg("车站已存在！");
        }
        InputStream is = myfile.getInputStream();

        String key = UUID.randomUUID().toString();
        QiniuOssUtils utils = new QiniuOssUtils();
        String path = utils.upload(is, key);

        station.setImg(path);

        //执行添加
        boolean b = stationService.save(station);
        if(b){
            return R.ok().setData(station).setMsg("上传成功");
        }
        //失败时从云存储中同时删除文件
        utils.delete(key);
        return R.fail().setMsg("上传失败");
    }
    @Operation(summary = "车站修改",description = "需要提供车站id")
    @Parameters({
            @Parameter(name = "id",description = "要修改的车站id",required = true),
            @Parameter(name = "name",description = "修改后的车站",required = true),
    })
    @PutMapping("/station/update")
    public R modify(Station station,MultipartFile myfile) throws IOException {

            // 获取查询条件构造器
            QueryWrapper<Station> query = Wrappers.query(Station.class);
            query.eq("id", station.getId());
            // 查询是否存在对应ID的车站
            Station one = stationService.getOne(query);
            if (Objects.isNull(one)) {
                return R.fail().setMsg("车站不存在！");
            }
            InputStream inputStream = myfile.getInputStream();

            String key = UUID.randomUUID().toString();
            QiniuOssUtils utils = new QiniuOssUtils();
            String path = utils.upload(inputStream, key);

            station.setImg(path);
            boolean updateSuccess = stationService.updateById(station);
            if (updateSuccess) {
                return R.ok().setMsg("修改成功！").setData(station);
                }
                //失败时从云存储中同时删除文件
                utils.delete(key);
                return R.fail().setMsg("修改失败！");
        }
    @Operation(summary = "车站删除", description = "根据车站id删除记录，该操作为物理删除，请谨慎处理")
    @DeleteMapping("/station/del/{id}")
    public R del(@Parameter(description = "车站id") @PathVariable("id") Integer id){
        Station station = stationService.getById(id);
        if (Objects.isNull(station)){
            return R.fail().setMsg("该车站不存在！");
        }

        return stationService.removeById(id) ? R.ok().setMsg("删除成功").setData(station) : R.fail().setMsg("删除失败");
    }

    /**
     * 分页查询
     * @param page
     * @param limit
     * @return
     */
    @Operation(summary = "车站列表",description = "显示所有车站，含分页功能，需要提供当前页码（page），以及每页限制条数（limit）")
    @Parameters({
            @Parameter(name = "page",description = "当前页码",required = true),
            @Parameter(name = "limit",description = "每页的条数",required = true),
    })
    @GetMapping("/station/list")
    public R list(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "5") Integer limit){
//        执行分页查询
        List<Station> list = stationService.list(new Page<Station>(page, limit));
        long count = stationService.count();
        return R.ok().setData(list).setCount(count);
    }
    @Operation(summary = "查询所有火车站",description = "所有车站")
    @GetMapping("/station/listAll")
    public R queryAll(){
        List<Station> list = stationService.list();
        return R.ok().setMsg("查询成功").setData(list);
    }
}
